package com.yunxiangyue

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.yunxiangyue.app.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class rvListAdapter(val musicListItm: MutableList<musicListItem>) : RecyclerView.Adapter<rvListAdapter.ViewHolder>() {

    // 定义一个接口来处理长按事件
    interface OnItemLongClickListener {
        fun onItemLongClick(view:View,position: Int): Boolean
    }

    private var onItemLongClickListener: OnItemLongClickListener? = null

    fun setOnItemLongClickListener(listener: OnItemLongClickListener) {
        onItemLongClickListener = listener
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val musicImg: ImageView = view.findViewById(R.id.img)
        val muscTitle: TextView = view.findViewById(R.id.title)
        val downLoadInfo: TextView = view.findViewById(R.id.info_music)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.rv_item, parent, false)
        return ViewHolder(view)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val music = musicListItm[position]
        holder.musicImg.setImageBitmap(music.imgBit)
        holder.muscTitle.setText(music.title)
//        notifyItemChanged(position)
        // 设置长按事件监听器
        holder.itemView.setOnLongClickListener {
            onItemLongClickListener?.onItemLongClick(holder.itemView,position) ?: false
        }
        CoroutineScope(Dispatchers.Main).launch {
            notifyDataSetChanged()
        }
    }

    override fun getItemCount(): Int {
        return musicListItm.size
    }

    fun addItem(item: musicListItem) {
        musicListItm.add(item)
        notifyItemInserted(0)
    }

    //删除某一项
//    fun deleteItem(position: Int) {
//        if (position >= 0 && position < musicListItm.size) {
//            musicListItm.removeAt(position)
//            notifyItemRemoved(position)
//
//            for(i in position)
//        }
//    }

}